<template>
    <div class="app-container">
        <!-- 表格-条件筛区域  -->
        <div class="filter-container">
            <el-input placeholder="请输入标题" v-model="searchParam.SEARCH_LIKE_title" style="width: 200px;"
                      class="filter-item" @keyup.enter.native="handleFilter"/>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索</el-button>
            <el-button class="filter-item" type="default" icon="el-icon-search" @click="searchReset"> 重置</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                       @click="handleCreate"> 新增
            </el-button>
        </div>

        <!-- 表格-内容区域 -->
        <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row
                  style="width: 100%;">
            <el-table-column v-for="column in columns" :key="column.prop"
                             :prop="column.prop"
                             :label="column.label"
                             :width="column.width"
                             :align="column.align?column.align:'center'"
                             :min-width="column.minWidth"
                             :sortable="column.sortable"
                             :fixed="column.fixed"
                             :type="column.type" :formatter="column.formatter">
                <template slot-scope="scope">
                    <!-- 行内显示图片 -->
                    <img v-if="column.imgFlag==true"
                         :src=" scope.row[column.prop].indexOf('http://') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
                         width="60" height="60" class="img" alt=""/>
                    <!-- 行内显示开关按钮 -->
                    <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]" :active-value="1"
                               :inactive-value="0" disabled></el-switch>
                    <!-- 行内显示tag标签 -->
                    <span v-else-if="column.tagFlag==true">
                        <span v-for="item in column.tagFormatter" :key="item.value">
                            <el-tag v-if="item.value==scope.row[column.prop]" :type="item.type">{{ item.text }}</el-tag>
                        </span>
                    </span>
                    <!-- 处理区域 -->
<!--                    <span v-else-if="column.prop === 'city'">-->
<!--                        {{ scope.row['city'] | formatCity(areaList) }}-->
<!--                    </span>-->
                    <!-- 行内格式自定义 -->
                    <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
                    <!--默认显示文本-->
                    <span v-else>{{ scope.row[column.prop] }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="240" class-name="small-padding">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"> 编辑</el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)"> 删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 表格-页脚区域 -->
        <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum"
                    :limit.sync="pageRequest.pageSize" @pagination="getList"/>

        <!--新增编辑界面-->
        <el-dialog :title="operation?'新增':'编辑'" width="45%" top="5vh" :visible.sync="dialogFormVisible"
                   :close-on-click-modal="false">
            <el-form :model="dataForm" label-width="140px" :rules="dataFormRules" ref="dataForm" style="width: 80%">

                <el-form-item label="标题" prop="title">
                    <el-input v-model="dataForm.title" auto-complete="off" placeholder="请输入标题"/>
                </el-form-item>
                <el-form-item label="banner图片" prop="image">
                    <cm-upload v-model="dataForm.image"></cm-upload>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="dataForm.type" placeholder="请选择类型">
<!--                        <el-option label="引导页" :value="1"></el-option>-->
<!--                        <el-option label="启动页" :value="2"></el-option>-->
                        <el-option label="banner" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="跳转类型" prop="transType">
                    <el-select v-model="dataForm.transType" placeholder="请选择跳转类型">
                        <el-option label="无" :value="0"></el-option>
                        <el-option label="H5" :value="1"></el-option>
                        <el-option label="直播间" :value="2"></el-option>
                        <el-option label="报名" :value="3"></el-option>
                        <el-option label="新闻" :value="4"></el-option>
                        <el-option label="球馆" :value="5"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.transType === 2" label="直播间列表" prop="liveRecordId">
                    <el-select  v-model="dataForm.liveRecordId" filterable placeholder="请选择跳转直播间">
                        <el-option v-for="item in liveRecordList"
                                   :key="item.id"
                                   :label="item.title"
                                   :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.transType === 3" label="报名列表" prop="matchId">
                    <el-select  v-model="dataForm.matchId" filterable placeholder="请选择跳转报名">
                        <el-option v-for="item in matchList"
                                   :key="item.id"
                                   :label="item.name"
                                   :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.transType === 4" label="新闻列表" prop="newsId">
                    <el-select  v-model="dataForm.newsId" filterable placeholder="请选择跳转新闻">
                        <el-option v-for="item in newsList"
                                   :key="item.id"
                                   :label="item.title"
                                   :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.transType === 5" label="球馆列表" prop="stationId">
                    <el-select  v-model="dataForm.stationId" filterable placeholder="请选择跳转球馆">
                        <el-option v-for="item in stationList"
                                   :key="item.id"
                                   :label="item.name"
                                   :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item    label="跳转参数json" prop="transParam">
                    <el-input v-model="dataForm.transParam" auto-complete="off" placeholder="请输入跳转参数json"/>
                </el-form-item>
<!--                <el-form-item label="展示位置" prop="location">-->
<!--                    <el-input v-model="dataForm.location" auto-complete="off" placeholder="请输入展示位置"/>-->
<!--                </el-form-item>-->
                <el-form-item label="是否展示" prop="isShow">
                    <el-switch v-model="dataForm.isShow" :active-value="1"
                               :inactive-value="0"></el-switch>
                </el-form-item>
                <el-form-item label="展示地域-城市" prop="city">
                    <el-cascader
                        ref="areaCascade"
                        v-model="dataForm.city"
                        :options="areaData"
                        :props="props"
                        collapse-tags
                        clearable
                        separator=" "
                        @change="handleChange"
                        style="width: 300px"
                    />
                    <br>
                    <span style="color:red;font-size:12px">提示：如果不选城市，则默认为全国</span>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeDialog()">取消</el-button>
                <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交
                </el-button>
            </div>
        </el-dialog>


    </div>
</template>
<script>
import _ from "lodash";
import Pagination from '@/components/Pagination' // 分页栏信息
import {deleteJdBanner, editJdBanner, getJdBannerList, saveJdBanner,getLiveRecordList,getMatchList,getNewsList,getStationList} from '@/api/modules/banner'
import CmUpload from '@/components/Upload'
import {getListByTypeId} from "@/api/modules/match"; // 上传图片组件引入

const areaList = require('./city')

export default {
    name: 'banner',
    components: {
        Pagination,
        CmUpload,
    },
    directives: {},
    filters: {
        // formatCity(value, list) {
        //     const item = list.find(item => item.code === value)
        //     return item ? item.name : ""
        // }
    },
    data() {
        return {
            tableKey: 0,
            tableList: [],//表格数据源
            tableTotal: 0,//表格总条数数据
            listLoading: true,
            pageRequest: {pageNum: 1, pageSize: 10,},
            searchParam: {},
            dialogFormVisible: false,//默认不显示弹出框
            operation: true, // true:新增, false:编辑
            editLoading: false,//保存表单时loading框
            liveRecordList:[],
            matchList:[],
            newsList:[],
            stationList:[],
            columns: [
                // {prop: 'id', label: '', sortable: false},
                {prop: 'title', label: '标题', sortable: false},
                {prop: 'image', label: 'banner图片', sortable: false, imgFlag: true},
                {
                    prop: 'type', label: '类型', sortable: false, tagFlag: true,
                    tagFormatter: [
                        {text: '引导页', value: 1, type: 'error'},
                        {text: '启动页', value: 2, type: 'success'},
                        {text: 'banner', value: 3, type: 'warning'},
                    ]
                },
                {
                    prop: 'transType', label: '跳转类型', sortable: false,tagFlag: true,
                    tagFormatter: [
                        {text: 'H5', value: 1, type: 'error'},
                        {text: '直播间', value: 2, type: 'success'},
                        {text: '报名', value: 3, type: 'success'},
                        {text: '新闻', value: 4, type: 'success'},
                        {text: '球馆', value: 5, type: 'success'},
                        {text: '无', value: 0, type: 'warning'},
                    ]
                },
                // {prop: 'transParam', label: '跳转参数json', sortable: false},
                // {prop: 'location', label: '展示位置', sortable: false},
                {prop: 'isShow', label: '是否展示', sortable: false, switchFlag: true,},
                // {prop: 'city', label: '展示地域-城市', sortable: false,formatter:this.getCityName},
            ],
            fileList: [],
            // 新增编辑界面数据
            dataForm: {},
            areaCasResult: {
                provinceCode: '',
                cityCode: '',
            },
            //表单检验规则
            dataFormRules: {
                // id: [{required: true, message: '请输入', trigger: 'blur'}],
                title: [{required: true, message: '请输入标题', trigger: 'blur'}],
                image: [{required: true, message: '请输入banner图片', trigger: 'blur'}],
                type: [{required: true, message: '请输入类型', trigger: 'blur'}],
                transType: [{required: true, message: '请输入跳转类型', trigger: 'blur'}],
                // transParam: [{required: true, message: '请输入跳转参数json', trigger: 'blur'}],
                // location: [{required: true, message: '请输入展示位置', trigger: 'blur'}],
                // isShow: [{required: true, message: '请输入是否展示0隐藏1展示', trigger: 'blur'}],
            },

            areaData: areaList,
            props: {
                multiple: false, // 是否多选
                emitPath: false,
                label: 'name',
                value: 'code',
                children: 'children'
            }
        }
    },
    methods: {
        //获取表格数据
        getList() {
            this.listLoading = true
            //【API请求】----获取表格列表数据
            getJdBannerList(this.pageRequest).then(response => {
                response = response.result
                this.tableList = response.content
                this.tableTotal = response.total
                this.listLoading = false;
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //表格数据筛选
        handleFilter() {
            this.pageRequest.searchParam = this.searchParam
            this.getList()
        },
        //【按钮点击】--- 弹出新增表单
        handleCreate() {
            this.operation = true;
            this.initDataForm();
            this.areaCasResult = {}
            this.dialogFormVisible = true
            this.getLiveRecordList()
            this.getMatchList()
            this.getNewsList()
            this.getStationList()
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                this.editLoading = false;
            })
        },
        //【按钮点击】--- 弹出编辑表单
        handleUpdate(row) {
            this.operation = false;
            const provinceCode = row.province + ""
            const cityCode = row.city + ""
            this.areaCasResult = {provinceCode, cityCode}
            this.dataForm = Object.assign({}, row)
            let liveRecordIdVulue
            if (row.transType === 2) {
                let jsonObj = JSON.parse(row.transParam)
                for (var item in jsonObj) {
                    if (item === "liveRecordId") { //item 表示Json串中的属性，如'name'
                        const liveRecordIdVulue = jsonObj[item]//key所对应的value
                        this.dataForm.liveRecordId = parseInt(liveRecordIdVulue)
                    }
                }
            }
            if (row.transType === 3 || row.transType === 4 || row.transType === 5) {
                let jsonObj = JSON.parse(row.transParam)
                for (var item in jsonObj) {
                    if (item === "id") { //item 表示Json串中的属性，如'name'
                        const id = jsonObj[item]//key所对应的value
                        if(row.transType === 3){
                            this.dataForm.matchId = parseInt(id)
                        }else if(row.transType === 4){
                            this.dataForm.newsId = parseInt(id)
                        }else if(row.transType === 5){
                            this.dataForm.stationId = parseInt(id)
                        }
                    }
                }
            }
            //显示编辑菜单
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                this.editLoading = false;
            })
        },
        //保存表单数据
        saveFormData() {
            let res
            this.$refs['dataForm'].validate(async (valid) => {
                if (!valid) {
                    return false;
                }
                this.editLoading = true;
                if(this.dataForm.transType === 2){//2 直播间
                    if(!this.dataForm.liveRecordId){
                        this.$notify({title: '失败', message: '请选择跳转直播间', type: 'error', duration: 2000})
                        this.editLoading = false// 关闭loading框
                        return;
                    }
                }
                if(this.dataForm.transType === 3){//3 赛事列表
                    if(!this.dataForm.matchId){
                        this.$notify({title: '失败', message: '请选择跳转报名', type: 'error', duration: 2000})
                        this.editLoading = false// 关闭loading框
                        return;
                    }
                }
                if(this.dataForm.transType === 4){//4 新闻列表
                    if(!this.dataForm.newsId){
                        this.$notify({title: '失败', message: '请选择跳转新闻', type: 'error', duration: 2000})
                        this.editLoading = false// 关闭loading框
                        return;
                    }
                }
                if(this.dataForm.transType === 5){//4 场馆列表
                    if(!this.dataForm.stationId){
                        this.$notify({title: '失败', message: '请选择跳转场馆', type: 'error', duration: 2000})
                        this.editLoading = false// 关闭loading框
                        return;
                    }
                }

                //【API请求】----保存数据
                if(this.dataForm.transType === 0){//如果是无，json啥也不填
                    this.dataForm.transParam = ''
                }
                if(this.dataForm.transType && this.dataForm.transType === 2){//如果是直播间
                    this.dataForm.transParam = this.dataForm.liveRecordId
                }
                if(this.dataForm.transType && (this.dataForm.transType === 3)){//如果是赛事
                    this.dataForm.transParam = this.dataForm.matchId
                }
                if(this.dataForm.transType && (this.dataForm.transType === 4)){//如果是新闻
                    this.dataForm.transParam = this.dataForm.newsId
                }
                if(this.dataForm.transType && (this.dataForm.transType === 5)){//如果是场馆
                    this.dataForm.transParam = this.dataForm.stationId
                }

                if (this.dataForm.id === null || this.dataForm.id === '') {
                    res = await saveJdBanner(this.dataForm)
                } else {
                    res = await editJdBanner(this.dataForm)
                }
                try {
                    if (res.code === 0) {
                        this.dialogFormVisible = false// 关闭表单页面
                        this.initDataForm()// 重置表单数据
                        this.getList()// 重新获取表格数据
                        this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
                    }
                    this.editLoading = false// 关闭loading框
                } catch (e) {
                    throw e
                }
            })
        },
        // 初始化省市区数据
        handleChange(value) {
            if (value != null) {
                const _value = _.cloneDeep(value) // 数据深克隆  避免回显问题
                if (_value.length !== 0) {
                    const result = {
                        address: this.$refs.areaCascade.getCheckedNodes()[0].pathLabels.join(''),
                        provinceCode: _value[0],
                        cityCode: _value[1] !== undefined ? _value[1] : '',
                    }
                    this.$emit('input', result)
                }
            }
        },
        //【按钮点击】---删除行
        handleDelete(row) {
            this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
                //【API请求】---- 删除数据
                deleteJdBanner(row.id).then(() => {
                    this.$message({message: '操作成功', type: 'success'})
                    this.getList();
                })
            }).catch(() => {
                this.$message({message: '操作失败', type: 'error'})
            });
        },
        //初始化表单数据，重新渲染
        initDataForm() {
            this.dataForm = {
                id: '',
                title: '',
                type: '',
                transType: '',
                transParam: '',
                location: '',
                isShow: 1,
                city: '',
                image: '',
            };
        },
        //关闭表单弹出框
        closeDialog() {
            this.$refs['dataForm'].resetFields();
            this.dialogFormVisible = false
        },
        // 重置按钮
        searchReset() {
            this.searchParam = {}
            this.pageRequest = {pageNum: 1, pageSize: 10}
            this.getList()
        },
        getLiveRecordList(liveRecordName) {
            getLiveRecordList({liveRecordName: liveRecordName}).then(response => {
                this.liveRecordList = response.result
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        getMatchList(matchName) {
            getMatchList({matchName: matchName}).then(response => {
                this.matchList = response.result
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        getNewsList(newsName) {
            getNewsList({newsName: newsName}).then(response => {
                this.newsList = response.result
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        getStationList(stationName) {
            getStationList({stationName: stationName}).then(response => {
                this.stationList = response.result
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        getCityName(row){
            // if(areaList!=null  && areaList.length>0){
            //     for(var i=0; i<areaList.length;i++){
            //         var province=areaList[i];
            //         if(province.code === row.city){
            //             return province.name
            //         }else{
            //             if(province.children){
            //                 var cityList = province.children;
            //                 if(cityList != null  && cityList.length>0){
            //                     for(var i=0; i < cityList.length;i++){
            //                         var city=cityList[i];
            //                         if(city.code === row.city){
            //                             return city.name
            //                         }
            //                     }
            //                 }
            //             }
            //         }
            //     }
            // }
        }
    },
    created() {
        this.getList();
        this.getLiveRecordList();
        this.getMatchList();
        this.getNewsList();
        this.getStationList();
    },
}
</script>
